package com.yesun.dcm.config.spring;

import com.yesun.dcm.config.spring.handler.DcmNamespaceHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chunmingdeng 2017/9/27 Create.
 * @version 1.0
 * @copyright (c) YESUN. All Rights Reserved.
 * @description:
 */
public class ServiceConfigBean<T> extends ServiceConfig<T> implements BeanFactoryAware, ApplicationContextAware, InitializingBean, DisposableBean, ApplicationListener<ContextRefreshedEvent> {

    private static final Logger log = LoggerFactory.getLogger(ServiceConfigBean.class);
    private transient BeanFactory beanFactory;

    @Override
    public void afterPropertiesSet() throws Exception {
        //配置注册中心
        configRegistry();
        //配置协议
        configProtocol();
    }

    private void configRegistry() {
        for (String name : DcmNamespaceHandler.registryDefineNames) {
            RegistryConfig registoryConfig = beanFactory.getBean(name, RegistryConfig.class);
            setRegistryConfig(registoryConfig);
        }
    }

    private void configProtocol() {
        List<ProtocolConfig> protocols = new ArrayList<ProtocolConfig>();
        for (String name : DcmNamespaceHandler.protocolDefineNames) {
            ProtocolConfig protocolConfig = beanFactory.getBean(name, ProtocolConfig.class);
            setProtocolConfig(protocolConfig);
        }
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    @Override
    public void destroy() throws Exception {
        log.debug("destroy service.");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        String serviceName = interfaceClass.getName();
        if (!"".equals(serviceName) && serviceName.length() != 0)
            handlerMap.putIfAbsent(serviceName, ref); //目的就是要将接口和服务实例存入map；一个服务只有一个实例；
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        // 发布服务
        if (getExported().get()) { //可能会重复执行，所以需要加上判断，当然也可以使用这个判断 if(event.getApplicationContext().getParent() == null){
            log.info("service is exported");
            return;
        }
        export();
    }
}
